import React, { Component } from 'react'
import {
  Card,
  Breadcrumb,
  Form,
  Space,
  Button,
  Input,
  Radio,
  Upload,
  Modal,
  message,
} from 'antd'
import { Link } from 'react-router-dom'
import MyChannel from 'components/MyChannel'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import styles from './index.module.scss'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from 'utils/request'
import { addArticles, getArticlesById, editArticlesById } from 'api/articles'

export default class ArticlePublish extends Component {
  state = {
    type: 1,
    fileList: [],
    previewVisible: false,
    previewImage: '',
    isEdit: !!this.props.match.params.id,
    id: this.props.match.params.id,
  }
  formRef = React.createRef()
  render() {
    const { type, fileList, previewVisible, previewImage, isEdit } = this.state
    return (
      <div className={styles.articlePublish}>
        <Card
          title={
            <Breadcrumb separator=">">
              <Breadcrumb.Item>
                <Link to="/home">首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>
                {isEdit ? '文章编辑' : '文章发布'}
              </Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            ref={this.formRef}
            initialValues={{ title: '', content: '', type }}
            labelCol={{ span: 4 }}
            size="large"
            onFinish={this.onFinish}
          >
            <Form.Item
              label="标题"
              name="title"
              rules={[{ required: true, message: '请输入文章标题' }]}
            >
              <Input placeholder="请输入文章标题" />
            </Form.Item>
            <Form.Item
              label="频道"
              name="channel_id"
              rules={[{ required: true, message: '请输入频道' }]}
            >
              <MyChannel />
            </Form.Item>
            <Form.Item label="封面" name="type">
              <Radio.Group onChange={this.handleTypeChange}>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
                <Radio value={0}>无图</Radio>
              </Radio.Group>
            </Form.Item>

            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  listType="picture-card"
                  fileList={fileList}
                  action={`${baseURL}/upload`}
                  name="image"
                  method="post"
                  onChange={this.handleFileChange}
                  onPreview={this.handlepreview}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && <PlusOutlined />}
                </Upload>
              </Form.Item>
            )}

            <Form.Item
              label="内容"
              name="content"
              rules={[{ required: true, message: '请输入文章内容' }]}
            >
              <ReactQuill
                theme="snow"
                placeholder="请输入文章内容..."
              ></ReactQuill>
            </Form.Item>
            <Form.Item wrapperCol={{ offset: 4 }}>
              <Space>
                <Button size="large" type="primary" htmlType="submit">
                  {isEdit ? '修改文章' : '发布文章'}
                </Button>
                <Button size="large" onClick={this.addDraft}>
                  存入草稿
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>

        <Modal
          visible={previewVisible}
          title="预览图片"
          footer={null}
          onCancel={this.handleCancel}
        >
          <img alt="example" style={{ width: '100%' }} src={previewImage} />
        </Modal>
      </div>
    )
  }

  async componentDidMount() {
    const { isEdit, id } = this.state
    if (isEdit) {
      // 根据id发送请求
      const {
        data: { title, channel_id, content, cover },
      } = await getArticlesById(id)
      // state 中 type 和 fileList 需要更新
      this.setState({
        type: cover.type,
        fileList: cover.images.map((item) => ({ url: item })),
      })
      // 表单中的数据也需要更新
      this.formRef.current.setFieldsValue({
        title,
        channel_id,
        content,
        type: cover.type,
      })
    }
  }

  beforeUpload = (file) => {
    if (file.size / 1024 > 500) {
      message.error('上传的图片过大，不能超过500KB')
      return Upload.LIST_IGNORE
    }
    console.log(file)
    if (!['image/jpeg', 'image/png'].includes(file.type)) {
      message.error('图片类型，仅支持jpeg，png')
      return Upload.LIST_IGNORE
    }
    return true
  }

  handlepreview = (file) => {
    this.setState({
      previewVisible: true,
      previewImage: file.url || file.response.data.url,
    })
  }

  handleCancel = () => {
    this.setState({
      previewVisible: false,
      previewImage: '',
    })
  }

  handleTypeChange = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }

  handleFileChange = ({ file, fileList }) => {
    this.setState({
      fileList,
    })
  }

  // 确认
  save = async (values, draft) => {
    const { fileList, isEdit, id } = this.state
    const { type } = values
    if (type !== fileList.length) {
      message.error('上传封面的数量不符')
      return
    }

    const imagesArr = fileList.map((item) => item.url || item.response.data.url)
    const data = {
      ...values,
      cover: {
        type: values.type,
        images: imagesArr,
      },
    }

    if (isEdit) {
      // 编辑修改文章
      await editArticlesById(id, data, draft)
      message.success('修改成功')
    } else {
      // 添加发布文章
      await addArticles(data, draft)
      message.success('发布成功')
    }
    this.props.history.push('/home/list')
  }

  // 表单
  onFinish = async (values) => {
    this.save(values, false)
  }

  // 存入草稿
  addDraft = async () => {
    try {
      const values = await this.formRef.current.validateFields()
      this.save(values, true)
    } catch (err) {
      message.error('校验未通过')
    }
  }
}
